<script setup>
import {defineEmits, inject, reactive, ref, watch} from "vue";
import 'jiuqi-ui';
import {useDialog} from "jiuqi-ui";
import {Debounce} from "../../../utils/debounce";
import TreeToTableSelector from "./TreeToTableSelector.vue";

//================================================【组件通信】============================================================
//控制 动因详情模态框 显示与隐藏
const driverDetailVisiable = inject('driverDetailVisiable');

//控制  动因项详情模态框 显示与隐藏
const driverItemDetailVisiable = inject('driverItemDetailVisiable')

//获取已经配置的动因维度信息
const dimInfoArr = inject('dimInfoArr')

const context = inject('context')

const {currAbcModelGuid} = inject('abcmodel')

//获取父组件传递的数据
const props = defineProps({
    selectedDriverItemArr: {
        type:Array,
        required:false
    },
    processType:{
        type:Number,
        required:true
    }
});

//与 父组件 通信
const emits = defineEmits(['selfConfirmReturnParam']);
//================================================【公用相关】============================================================
//动因项详情模态框 标题
const modalTitle = ref('动因项详情')
//清空数据，保证前后两次打开模态框，数据互不影响
function clearDataRecord(){
  selectedDim.name = ''
  selectedDim.title = ''
    treeData.splice(0,treeData.length)
    rightTableData.splice(0,rightTableData.length)
}
//选择维度
const selectedDim = reactive({
  name:'',
  title:''
})

//树形数据
const treeData = reactive([])

//表格数据 维度项信息
let rightTableData = reactive([])
//================================================【组件属性】============================================================
//监听 当前组件显示与否 ，进行下拉框初始化
watch(driverItemDetailVisiable,(newValue)=>{
    if (newValue) {
        initDropDownSelect()
    }
},{immediate:true})

//当 下拉选择值 不为空字符串时，获取树形数据
watch(()=>selectedDim.name,(newValue,oldValue)=>{
    //当维度切换时，右侧表格过滤关键词应该清空
    if (newValue && newValue.value !== '') {
        //当切换维度后，右侧表格内容清空
        if (oldValue !== '') {
            rightTableData.splice(0,rightTableData.length)
        }
        //重新加载树形
        getTreeData(newValue)
      let findedItem = preSelectDim.find(preFindItem => {
        return preFindItem.name === newValue
      })
      if (findedItem)
        selectedDim.title = findedItem.title
    }
},{deep:true})

//处理器编辑模式下，将会 由 父组件传递 指定维度编码 下 选择的 动因项信息（可以看做维度项信息）
watch(()=>props.selectedDriverItemArr,(newValue)=>{
    let length = newValue.length;
    if (length > 0 && rightTableData.length === 0) {

        for (let i = 0; i < length; i++) {
             //回显 之前添加的维度项，用于编辑操作
            rightTableData.push(newValue[i])
        }

      selectedDim.name = rightTableData[0].dimName
    }
},{deep:true})

//================================================【普通方法】============================================================
//==================================================================【下拉选项】
const preSelectDim = reactive([])
function initDropDownSelect() {
    context.getPlugin('http').get(`abc/model/dimension/all/${currAbcModelGuid.value}`).then((res) => {
        preSelectDim.splice(0, preSelectDim.length, ...res.data.allDimBeanVoList)

        //将 父组件中已经 有的 维度 进行过滤
        const tempArr = preSelectDim.filter(preFilterItem => {
            return setOptionItemDisable(preFilterItem.name)
        })

        preSelectDim.splice(0, preSelectDim.length, ...tempArr)
    })
}

//设置下拉选项隐藏（隐藏 DriverDetail 中 dimInfoArr 里 已经存在的维度）
function setOptionItemDisable(dimName) {
    //添加操作，筛除全部已选维度
    if (props.processType === 0){
        for (let dimInfoArrElement of dimInfoArr) {
            if (dimInfoArrElement.dimName === dimName){
                return false
            }
        }
        return true
    }

    //编辑操作，筛除全部已选维度（保留当前编辑维度）
    if (props.processType === 1) {
        if (props.selectedDriverItemArr[0].dimName === dimName) {
            return true
        }else {
            for (let dimInfoArrElement of dimInfoArr) {
                if (dimInfoArrElement.dimName === dimName){
                    return false
                }
            }
            return true
        }
    }
}
//==================================================================【搜索框相关】
  let defaultConfigs = {};
  defaultConfigs.leftTreeShowAttribute = [ "code","name" ];
  defaultConfigs.leftTableColumns =
      [{
        title: '编码',
        key: 'dimItemCode',
        width: 200,
        align: 'left'
      },
        {
          title: '名称',
          key: 'dimItemName',
          width: 200,
          align: 'left'
        }];
  defaultConfigs.rightTableSearchKeys = [ "dimItemCode","dimItemName" ];
  defaultConfigs.rightTableColumns =
      [{
        title: '编码',
        key: 'dimItemCode',
        width: 200,
        align: 'left'
      },
        {
          title: '名称',
          key: 'dimItemName',
          width: 200,
          align: 'left'
        }];
//左侧 树形 模糊匹配
function fuzzyLeftMatch(searchWord,handleSearchResult) {
        //构建请求参数对象
        const requestItem = reactive({
            modelId: currAbcModelGuid.value,
            dimName: selectedDim.name,
            searchKey:searchWord
        })
        Debounce(  context.getPlugin('http').post(`abc/model/dimension/member/fuzzyMatch`, requestItem).then((res) => {
          handleSearchResult(res.data.matchedDimMemberList)
        }),300)()
}

//获取维度项树形数据 (根节点)
function getTreeData(dimName) {
    //获取指定  多个维度 下的所有  维度项
    const requestItem = reactive({
        modelId: currAbcModelGuid.value,
        dimName: dimName
    })
    context.getPlugin('http').post(`abc/model/dimension/member/byDimName`, requestItem).then((res) => {
      treeData.splice(0,treeData.length,...res.data.showList)
    })
}
//==================================================================【确认操作】
const dialogPop = useDialog()
const loading = ref(false)
function selectorConfirm() {
    if (loading.value) {
        return
    }

    loading.value = true

    //判断用户当前是否选择维度信息
    if (selectedDim.name === '') {
        dialogPop.warning({
            title: '操作异常',
            content: `未选择维度`,
        });
        loading.value = false

        //判断用户当前是否选择维度项信息
    }else if (rightTableData.length === 0) {
        dialogPop.warning({
            title: '操作异常',
            content: `未选择维度项`,
        });
        loading.value = false

    }else {
        loading.value = false
      let processedResultArr = []
      for (let rightTableDatum of rightTableData) {
        let item = {
          dimName:selectedDim.name,
          dimTitle:selectedDim.title,
          ...rightTableDatum
        }
        processedResultArr.push(item)
      }
        emits('selfConfirmReturnParam',processedResultArr);
        clearDataRecord();
        driverDetailVisiable.value = true;
        driverItemDetailVisiable.value = false;
    }
}

//==================================================================【取消操作】
function selectorCancel() {
    clearDataRecord()
    driverDetailVisiable.value = true
    driverItemDetailVisiable.value = false
}
//==================================================================【关闭选择模态框】
function getVisibleChange(info) {
    //当 动因详情模态框 关闭时
    if (info === false) {
        //动因项详情模态框 需要保持显示
        driverDetailVisiable.value = true
    }
}
//================================================【生命周期】============================================================
</script>

<template>
    <j-modal
        v-model="driverItemDetailVisiable"
        :title="modalTitle"
        :fullscreenable='false'
        :mask="false"
        :mask-closable="false"
        :closable="!loading"
        @visible-change="getVisibleChange"
    >
        <j-modal-content size="large">
            <div>可选维度</div>
            <j-select
                v-model="selectedDim.name"
                width="398px"
                style="margin-bottom: 20px"
                placeholder="请选择维度"
            >
                <j-option v-for="(item) in preSelectDim"
                          :key="item.guid"
                          :value="item.name"
                          :label="item.title"
                >
                </j-option>
            </j-select>
            <TreeToTableSelector
                search-prompt-words="请输入编码或名称进行查询"
                left-component-title="可选维度成员"
                right-component-title="已选维度成员"
                :configs="defaultConfigs"
                :left-tree-init-data="treeData"
                v-model:right-table-result-data="rightTableData"
                @leftTreeFuzzyMatch="fuzzyLeftMatch">
            </TreeToTableSelector>
        </j-modal-content>
        <template #footer>
           <j-space style="justify-content: flex-end">
               <j-button @click="selectorCancel" :disabled='loading'>取消</j-button>
               <j-button type="primary" :loading='loading' @click="selectorConfirm">确定</j-button>
           </j-space>
        </template>
    </j-modal>
</template>

<style scoped>
</style>
